package com.zy.validated.controller;


import com.zy.validated.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author 11473
 * @version 1.0
 * @date 2019/11/17 18:03
 */
@Controller
public class Test {

    /**
     * 验证bean User的格式  必须加注解：@Validated ，
     * 校验的信息会传递到这个参数之后的参数 BindingResult 中 ，
     * 可以从其中提取出错误的信息
     * @param user
     * @param result
     * @return
     */
    @RequestMapping("/test")
    @ResponseBody
    public String test(@Validated User user, BindingResult result){

        if(result.hasErrors()){
            ObjectError s = result.getAllErrors().get(0);
            String msg = s.getDefaultMessage();
            return msg;
        }
        System.out.println(user.toString());
        return "格式正确";
    }

}
